const app = getApp();
var QQMapWX = require('../../resource/js/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({
  data: {
    xian:true,
    show: true,
    hidden: true,
    array: ['美国', '中国', '巴西', '日本'],
    sexArray: ['只限男性','只限女性'],
    weightArray: ['5KG以下','5KG以上'],
    tip:['不加','5','10','15','20','25'],
    origin:'请选择购买地址',
    tip_num:0,
    origin_latitude:0,
    origin_longitude:0,
    destination:'请选择收货地址',
    destination_latitude:0,
    destination_longitude:0,
    destination_phone:0,
    destination_id:0,
    tip_text:'接单更快，购买更及时',
    index: 0,
    sexIndex:0,
    weightIndex:0,
    weightStyle:false,
    sexStyle:false,
    timeStyle:false,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    index: 0,
    priceInput:1,
    isCity:true,
    day:['今天','明天'],
    when:[],
    points:[],
    day_index:0,
    when_index:0,
    points_index:0,
    dateValue: [0, 0, 0],
    certification:false,
    coupons_num:0,
    list:{},
    content:'',
    coupons:{},
    couponsStyle:true,
    total_price:0,
    userInfo:{},
    weightGong:"",
    weight:'',
  },
  bindChange:function(e){
    console.log(e.detail.value);
  },
  succeedWeight:function(){
    const that = this;
    var list = that.data.list;
    if (that.data.weightGong === ''){
      that.setData({
        weight:'小于5'
      })
    }else{
      var weightGong = that.data.weightGong;
      var total_price = that.data.total_price;
      var weights = that.data.weight;
      if(that.data.weight === '小于5'){
        that.setData({
          total_price: parseInt(total_price) + parseInt(weightGong - 5) * list['weight'],
          weight: that.data.weightGong
        })
      }else{
        that.setData({
          total_price: total_price - parseInt(weights - 5) * list['weight'] + parseInt(weightGong - 5) * list['weight'],
          weight: that.data.weightGong
        })
      }
      
    }
    that.setData({
      weightStyle:true,
      modalName:null
    })
  },
  sliderChange:function(e){
    const that = this;
    that.setData({
      weightGong: e.detail.value
    })
  },
  showModal(e){
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  origin:function(){
    wx.navigateTo({
      url: '../map/map?type=origin'
    })
  },
  destination: function(){
    wx.navigateTo({
      url: '../map/map?type=destination'
    })
  },
  risePicker:function(e){
    var that = this;
    if (that.data.dateValue[0] === 0) {
      var date = new Date();
      var hours = date.getHours() + 3;
      var day_hours = 24;
      var evn_hours = day_hours - hours;
      var when = new Array();
      for (var i = evn_hours; i >= 0; i--) {
        when[i] = hours + i;
      }
      when.unshift('立即配送');
      that.setData({
        when: when
      })
      if (that.data.dateValue[1] === 0) {
        that.setData({
          points: {}
        })
      } else {
        that.setData({
          points: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
        })
      }
    } else {
      that.setData({
        when: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        points: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
      })
    }
    var mold = e.currentTarget.dataset.mold;
    if(mold === 'dateTime'){
      that.setData({
        isDate: true
      })
    }
  },
  ideChoice:function(e){
    var that = this;
    that.setData({
      isDate: false
    })
  },
  determine:function(e){
    var that = this;
    if (that.data.dateValue[0] === 0){
      that.setData({
        day_index:-1
      })
    }
    that.setData({
      isDate: false,
      timeStyle: true
    })
  },
  priceInput:function(e){
    const that = this;
    const str = e.detail.value;
    var re = /^[0-9]+.?[0-9]*$/;
    if(!re.test(str)){
      wx.showToast({
        title: '请输入数字',
        icon: 'none',
        duration: 2000
      });
      that.setData({
        priceInput: 1
      })
    }else{
      that.setData({
        priceInput: e.detail.value
      })
    }
  },
  priceInputs:function(){
    const that = this;
    const data = that.data.tip;
    that.setData({
      tip_num:data.length
    })
  },
  errandsTip:function(e){
    const that = this;
    that.setData({
      tip_num: e.target.dataset.index
    })
  },
  bindGetUserInfo:function(e){
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success(a) {
              var str = JSON.parse(a.rawData);
              wx.login({
                success(res) {
                  if (res.code) {
                    app.util.request({
                      url: 'Index/Index/getOpenid',
                      data: {
                        avatarUrl: str.avatarUrl,
                        city: str.city,
                        country: str.country,
                        gender: str.gender,
                        language: str.language,
                        nickName: str.nickName,
                        province: str.province,
                        code: res.code
                      },
                      header: {
                        'content-type': 'application/json'
                      },
                      success(res) {
                        app.globalData.userInfo = res.data;
                        that.setData({
                          userInfo: res.data,
                          certification:true
                        })
                        app.util.request({
                          url: 'Index/Index/getChargeRules', // 仅为示例，并非真实的接口地址
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success(res) {
                            const data = res.data;
                            var total_price = that.data.total_price;
                            total_price = total_price + parseInt(data.basis_cost);
                            that.setData({
                              list: res.data,
                              total_price: total_price
                            })
                          }
                        })
                        app.util.request({
                          url: 'Index/Index/getDefaultAddress',
                          data: {
                            openid: app.globalData.userInfo.openid
                          },
                          header: {
                            'content-type': 'application/json'
                          },
                          success(res) {
                            if (JSON.stringify(res.data) === '[]') {
                              that.setData({
                                destination: '请选择收货地址',
                                destination_latitude: 0,
                                destination_longitude: 0
                              })
                            } else {
                              that.setData({
                                destination: res.data.address + res.data.addressed,
                                destination_latitude: res.data.latitude,
                                destination_longitude: res.data.longitude,
                                destination_phone:res.data.phone,
                                destination_name: res.data.name
                              })
                            }
                          }
                        })
                        app.util.request({
                          url: 'Index/Index/getCouponsNum',
                          data: {
                            openid: app.globalData.userInfo.openid
                          },
                          header: {
                            'content-type': 'application/json'
                          },
                          success(res) {
                            that.setData({
                              coupons_num: res.data.coupons
                            })
                          }
                        })
                      }
                    })
                  } else {
                    console.log('登录失败！' + res.errMsg)
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  formSubmitOrder:function(e){
    const that = this;
    if (that.data.content === ''){
      wx.showToast({
        title: '下单内容不能为空',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (that.data.origin === '请选择购买地址'){
      wx.showToast({
        title: '请选择购买地址',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (that.data.destination === '请选择收货地址') {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (that.data.timeStyle === false){
      wx.showToast({
        title: '请选择送达时间',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (that.data.weightStyle === false){
      wx.showToast({
        title: '请选择物品重量',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (that.data.xian === false){
      wx.showToast({
        title: '请同意并接受《跑腿服务协议》',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    var sex_limit = 0;
    if (that.data.sexStyle === false){
      sex_limit = 2;
    }else{
      if (that.data.sexIndex === 0){
        sex_limit = 0;
      }else{
        sex_limit = 1;
      }
    }
    var depart_time = '';
    if (that.data.day[that.data.day_index] !== undefined && that.data.points[that.data.points_index] !== undefined){
      depart_time = that.data.day[that.data.day_index] + that.data.when[that.data.when_index] + ':' + that.data.points[that.data.points_index];
    } else if (that.data.day[that.data.day_index] === undefined && that.data.points[that.data.points_index] !== undefined){
      depart_time = that.data.when[that.data.when_index] + ':' + that.data.points[that.data.points_index];
    }else{
      depart_time = that.data.when[that.data.when_index];
    }
    var coupons_id = 0;
    if (JSON.stringify(that.data.coupons) != '{}'){
      coupons_id = that.data.coupons.id;
    }else{
      coupons_id = 0;
    }
    var weight = 0;
    if (that.data.weight === '小于5'){
      weight = 5;
    }else{
      weight = parseInt(that.data.weight);
    }
    var tip = 0;
    if (that.data.tip_text === '接单更快，购买更及时'){
      tip = 0;
    } else if (that.data.tip_text === '不加'){
      tip = 0;
    }else{
      parseInt(that.data.tip_text);
    }
    app.util.request({
      url: 'Index/Index/setOrderId',
      method: 'post',
      data: {
        buyers_openid: app.globalData.userInfo.openid,
        content: that.data.content,
        origin: that.data.origin,
        origin_longitude: that.data.origin_longitude,
        origin_latitude: that.data.origin_latitude,
        terminus: that.data.destination,
        terminus_longitude: parseFloat(that.data.destination_longitude),
        terminus_latitude: parseFloat(that.data.destination_latitude),
        destination_name: that.data.destination_name,
        phone: that.data.destination_phone,
        depart_time: depart_time,
        tip: tip,
        weight: weight,
        sex_limit: sex_limit,
        coupons_id: coupons_id,
        total_price: that.data.total_price
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        var data = res.data.data;
        app.startpay(data);
      }
    })
  },
  content:function(e){
    const that = this;
    that.setData({
      content:e.detail.value
    })
  },
  useCoupons:function(){
    const that = this;
    wx.navigateTo({
      url: '../coupon/coupon'
    })
  },
  dateChange:function(e){
    const that = this;
    if(that.data.dateValue[0] === 0){
      var date = new Date();
      var hours = date.getHours() + 3;
      var day_hours = 24;
      var evn_hours = day_hours - hours;
      var when = new Array();
      for (var i = evn_hours; i >= 0; i--) {
        when[i] = hours + i;
      }
      when.unshift('立即配送');
      that.setData({
        when:when
      })
      if (e.detail.value[1] === 0){
        that.setData({
          points:{}
        })
      }else{
        that.setData({
          points: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
        })
      }
    }else{
      that.setData({
        when: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        points: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
      })
    }
    that.setData({
      day_index: e.detail.value[0],
      when_index:e.detail.value[1],
      points_index:e.detail.value[2],
      dateValue:e.detail.value
    })
  },
  successfulTip:function(e){
    const that = this;
    const data = that.data.tip;
    const index = that.data.tip_num;
    if (data[index] === undefined){
      var total_price = that.data.total_price;
      if (that.data.tip_text === '接单更快，购买更及时'){
        total_price = total_price + parseInt(that.data.priceInput);
      }else if(that.data.tip_text === '不加'){
        total_price = total_price + parseInt(that.data.priceInput);
      }else{
        total_price = total_price - parseInt(that.data.tip_text) + parseInt(that.data.priceInput);
      }
      that.setData({
        tip_text: that.data.priceInput,
        modalName: null,
        total_price: total_price
      })
    }else{
      if(data[index] !== '不加'){
        var str = data[index];
        var total_price = that.data.total_price;
        var tip_text = that.data.tip_text;
        if (tip_text === '接单更快，购买更及时'){
          total_price = total_price + parseInt(str);
        }else if(tip_text !== '不加'){
          total_price = total_price - tip_text + parseInt(str);
        }else{
          total_price = total_price + parseInt(str);
        }
        that.setData({
          tip_text: data[index],
          modalName: null,
          total_price: total_price
        })
      }else{
        if (that.data.tip_text === '接单更快，购买更及时'){
          that.setData({
            tip_text: data[index],
            modalName: null
          })
        }else{
          var tip_text = that.data.tip_text;
          var total_price = that.data.total_price;
          total_price = total_price - tip_text;
          that.setData({
            tip_text: data[index],
            modalName: null,
            total_price: total_price
          })
        }
      }
    }
  },
  bindWeightPickerChange:function(e){
    const that = this;
    that.setData({
      weightIndex: e.detail.value,
      weightStyle: true
    })
  },
  bindSexPickerChange:function(e){
    const that = this;
    that.setData({
      sexIndex: e.detail.value,
      sexStyle: true
    })
  },
  agreement:function(){
    wx.navigateTo({
      url: '../certification/certification'
    })
  },
  hideModal(e){
    this.setData({modalName: null})
  },
  show:function(){
    var that = this;
    if (that.data.show == true){
      that.setData({show: false,hidden: false})
    }else{
      that.setData({show: true,hidden: true})
    }
  },
  shows:function(){
    var that = this;
    if (that.data.hidden == false){
      that.setData({hidden: true,show: true})
    } else {
      that.setData({hidden: false,show: false})
    }
  },
  onLoad: function (options){
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success(res) {
              var str = JSON.parse(res.rawData);
              wx.login({
                success(res) {
                  if (res.code) {
                    app.util.request({
                      url: 'Index/Index/getOpenid',
                      data: {
                        avatarUrl: str.avatarUrl,
                        city: str.city,
                        country: str.country,
                        gender: str.gender,
                        language: str.language,
                        nickName: str.nickName,
                        province: str.province,
                        code: res.code
                      },
                      header: {
                        'content-type': 'application/json'
                      },
                      success(res) {
                        app.globalData.userInfo = res.data;
                        that.setData({
                          userInfo: res.data,
                          certification: true
                        })
                        app.util.request({
                          url: 'Index/Index/getChargeRules', // 仅为示例，并非真实的接口地址
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success(res) {
                            const data = res.data;
                            var total_price = that.data.total_price;
                            total_price = total_price + parseInt(data.basis_cost);
                            that.setData({
                              list: res.data,
                              total_price: total_price
                            })
                          }
                        })
                        app.util.request({
                          url: 'Index/Index/getDefaultAddress',
                          data: {
                            openid: app.globalData.userInfo.openid
                          },
                          header: {
                            'content-type': 'application/json'
                          },
                          success(res) {
                            if (JSON.stringify(res.data) === '[]'){
                              that.setData({
                                destination: '请选择收货地址',
                                destination_latitude: 0,
                                destination_longitude: 0
                              })
                            }else{
                              that.setData({
                                destination: res.data.address + res.data.addressed,
                                destination_latitude: res.data.latitude,
                                destination_longitude: res.data.longitude,
                                destination_phone: res.data.phone,
                                destination_name: res.data.name
                              })
                            }
                          }
                        })
                        app.util.request({
                          url: 'Index/Index/getCouponsNum',
                          data: {
                            openid: app.globalData.userInfo.openid
                          },
                          header: {
                            'content-type': 'application/json'
                          },
                          success(res) {
                            that.setData({
                              coupons_num: res.data.coupons
                            })
                          }
                        })
                      }
                    })
                  } else {
                    console.log('登录失败！' + res.errMsg)
                  }
                }
              })
            }
          })
        } else {
          that.setData({
            certification:false
          })
          wx.showToast({
            title: '请点击收货地址获取授权信息',
            icon: 'none',
            duration: 2000
          });
          return false;
        }
      }
    })
  },
  address:function(){
    wx.navigateTo({
      url: '../address/address?type=order'
    })
  },
  price_rule:function(){
    const that = this;
    that.setData({
      modalName: null
    })
    wx.navigateTo({
      url: '../priceRule/priceRule'
    })
  },
  toggle(){
    var that=this;
    if(that.data.xian == true){
      that.setData({xian: false})
    }else{
      that.setData({xian:true})
    }
  },
  onShow:function(){
    const that = this;
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    if (currPage.data.address !== undefined){
      that.setData({
        destination: currPage.data.address,
        destination_latitude: currPage.data.latitude,
        destination_longitude: currPage.data.longitude,
        destination_phone: currPage.data.phone,
        destination_name: currPage.data.name
      })
    }
    if(JSON.stringify(currPage.data.coupons) != '{}'){
      var coupons = currPage.data.coupons;
      var total_price = that.data.total_price;
      that.setData({
        coupons: currPage.data.coupons,
        couponsStyle:false
      })
    }
    if (currPage.data.type){
      const data = currPage.data.localhost;
      const type = currPage.data.type;
      if (type === 'origin'){
        qqmapsdk = new QQMapWX({ key: 'KJHBZ-PMX6X-MXE44-TRKVY-LC6YQ-JYBTM' });
        qqmapsdk.reverseGeocoder({
          location:data.latitude + ',' + data.longitude,
          success:function(res){
            var start = that.data.destination_latitude + ',' + that.data.destination_longitude;
            var end = data.latitude + ',' + data.longitude;
            qqmapsdk.calculateDistance({
              from: start,
              to: end,
              success:function(res){
                var res = res.result;
                var m = res.elements[0].distance;
                var km = Math.floor(m / 1000);
                var list = that.data.list;
                var min_distance = parseInt(list['min_distance']);
                var max_distance = parseInt(list['max_distance']);
                var money = 0;
                if(km < 2){
                  that.setData({
                    origin: data.address,
                    origin_latitude: data.latitude,
                    origin_longitude: data.longitude
                  })
                  return false;
                }else if (2 <= km && km <= 4){
                  var distance = km - 2;
                  var total_price = that.data.total_price;
                  money = distance * min_distance;
                  total_price = total_price + money;
                  that.setData({
                    total_price: total_price
                  })
                  that.setData({
                    origin: data.address,
                    origin_latitude: data.latitude,
                    origin_longitude: data.longitude
                  })
                  return false;
                } else if (4 <= km && km <= 100){
                  var distance = km - 4;
                  var total_price = that.data.total_price;
                  money = distance * max_distance + min_distance * 2;
                  total_price = total_price + money;
                  that.setData({
                    total_price: total_price
                  })
                  that.setData({
                    origin: data.address,
                    origin_latitude: data.latitude,
                    origin_longitude: data.longitude
                  })
                  return false;
                } else {
                  currPage.setData({
                    type: '',
                    localhost: {}
                  });
                  wx.showToast({
                    title: '配送超出范围',
                    icon: 'none',
                    duration: 2000
                  });
                  return false;
                }
              }
            });
          }
        })
      }
    }
  }
})